<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/25
 * Time: 15:24
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\library\Tools;
use think\console\input\Option;
use think\Db;
use think\Exception;

class GenerateModel extends BaseCommand
{
    protected function configure()
    {
        // 指令配置
        $this->setName('generateModel')
            ->addOption("path", null, Option::VALUE_REQUIRED, "模型路径");
    }

    protected function handler()
    {
        $path = $this->input->hasOption('path')
                ? $this->input->getOption('path')
                : '';
        $this->generateModelName($path);
        $this->output->write("生成完成, 请检查是否有自动字段请自行添加\n");
    }

    /**
     * 自动生成数据库模型
     * @param string $modelPath 模型路径
     * @date 2020/07/02
     * @author longli
     * @throws Exception
     */
    protected function generateModelName($modelPath = '')
    {
        $tables = [];
        $modelPath = rtrim($modelPath, '/');
        foreach(Db::query("show tables") as $tableName)
        {
            $name = current($tableName);
            $className = ucfirst(Tools::toCamelCase($name));
            $tables[$name] = $className;
            $exec = sprintf("php think make:model common/%s%s", $modelPath ? "$modelPath/" : '', $className);
            exec($exec);
        }
        foreach($tables as $table => $fileName)
        {
            $file = "./application/common/model/$fileName.php";
            $content = file_get_contents($file);
            if(strpos($content,'$pk') !== false) continue;
            $desc = Db::query("desc $table");
            $pk = $desc[0]['Field'];
            if($pk == 'id') continue;
            $date = date('Y/m/d');
            $time = date('H:i');
            $authorInfo = <<<EOF
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: {$date}
 * Time: {$time}
 * @link http://www.lmterp.cn
 */
EOF;

            if($pk != 'id') $content = str_replace('//', "protected \$pk = '$pk';", $content);
            $content = str_replace(["<?php", "use think\\Model;\n", 'extends Model', "\n\n"], ["<?php\n$authorInfo\n", '', "extends BaseModel", "\n"], $content);
            file_put_contents($file, $content);
        }
    }
}
